package perform.lazy.impl;

import java.lang.reflect.Field;
import java.sql.Connection;

import perform.annotations.ManyToMany;
import perform.exception.UpdateException;
import perform.lazy.PerformUpdater;
import perform.mappings.ClassMappings;
import perform.query.impl.M2MDeleteQuery;
import perform.query.impl.M2MInsertQuery;
import perform.type.Type;

public class SimpleUpdater implements PerformUpdater {

	@Override
	public <T extends Type> void addManyToMany(Type source, Field sourceField,
			T target, Connection connection) throws UpdateException {
		try {
			M2MInsertQuery query = new M2MInsertQuery(ClassMappings.getManyToManyMapping(
					sourceField.getAnnotation(ManyToMany.class).table()), source, sourceField, target, connection);
			query.executeUpdate();
			query.close();
		} catch (Exception e) {
			throw new UpdateException(e);
		}
	}

	@Override
	public <T extends Type> void removeManyToMany(Type source,
			Field sourceField, T target, Connection connection)
			throws UpdateException {
		try {
			M2MDeleteQuery query = new M2MDeleteQuery(ClassMappings.getManyToManyMapping(
					sourceField.getAnnotation(ManyToMany.class).table()), source, sourceField, target, connection);
			query.executeUpdate();
			query.close();
		} catch (Exception e) {
			throw new UpdateException(e);
		}
	}

}
